import 'package:flutter/material.dart';
import './image.dart';
import 'dart:async';

class Swiper extends StatefulWidget {
  final double width;
  final double height;
  final List<String> list;

  const Swiper({
    super.key,
    this.width = double.infinity,
    this.height = 200,
    required this.list,
  });

  @override
  State<Swiper> createState() => _SwiperState();
}

class _SwiperState extends State<Swiper> {
  int _currentPageIndex = 0;
  List<Widget> pageList = [];
  // 1.定义 _pageController
  late PageController _pageController;
  late Timer periodicTimer;

  @override
  void initState() {
    super.initState();
    for (var i = 0; i < widget.list.length; i++) {
      pageList.add(
        ImagePage(
          width: widget.width,
          height: widget.height,
          src: widget.list[i],
        ),
      );
    }

    // 2.初始化 PageController
    _pageController = PageController(initialPage: 0);
    // 4.通过 _pageController 控制页面
    periodicTimer = Timer.periodic(
      const Duration(seconds: 3),
      (timer) {
        _pageController.animateToPage(
          (_currentPageIndex + 1) % pageList.length,
          duration: const Duration(milliseconds: 200),
          curve: Curves.linear,
        );
      },
    );
  }

  // 5.销毁定时器
  @override
  void dispose() {
    super.dispose();
    periodicTimer.cancel();
    _pageController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        SizedBox(
          height: 200,
          child: PageView.builder(
            // 3.配置 _pageController
            controller: _pageController,
            onPageChanged: (index) {
              setState(() {
                _currentPageIndex = index % pageList.length;
              });
            },
            itemCount: 1000,
            itemBuilder: (context, index) {
              return pageList[index % pageList.length];
            },
          ),
        ),
        Positioned(
          bottom: 10,
          left: 0,
          right: 0,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: List.generate(pageList.length, (index) {
              return Container(
                margin: const EdgeInsets.fromLTRB(2, 0, 2, 0),
                width: 7,
                height: 7,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color:
                      _currentPageIndex == index ? Colors.amber : Colors.grey,
                ),
              );
            }).toList(),
          ),
        ),
      ],
    );
  }
}
